<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('system.marketChannel.channelName')">
        <el-input
          v-model="form.name"
          clearable
          :placeholder="t('system.marketChannel.channelName')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('system.marketChannel.status')">
        <el-select
          v-model="form.status"
          :placeholder="t('system.marketChannel.status')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd">
        {{ t('system.marketChannel.add') }}
      </el-button>
      <el-button type="success" :disabled="!multipleSelection.length" @click="handleBatch('open')">
        {{ t('system.marketChannel.batchEnabled') }}
      </el-button>
      <el-button type="warning" :disabled="!multipleSelection.length" @click="handleBatch('close')">
        {{ t('system.marketChannel.batchShutdownStatus') }}
      </el-button>
      <!--      <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatch('delete')">-->
      <!--        {{ t('system.marketChannel.batchDelete') }}-->
      <!--      </el-button>-->
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('expandCustomer.serialNumber')" prop="id" min-width="250" />
      <el-table-column
        :label="t('system.marketChannel.channelName')"
        prop="name"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('system.marketChannel.maxCharacter')"
        prop="max_characters_num"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column :label="t('system.marketChannel.status')" min-width="250">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            inlinePrompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeStatus('single', row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('system.marketChannel.createdBy')"
        prop="creator"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('system.marketChannel.creationTime')"
        prop="create_time"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('system.marketChannel.updater')"
        prop="updater"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('system.marketChannel.updatedTime')"
        prop="update_time"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="{ row }">
          <el-button @click="handleEdit(row)" size="small">
            {{ t('system.marketChannel.edit') }}
          </el-button>
          <!--          <el-button @click="handleDelete('single', row)" size="small" type="danger">-->
          <!--            {{ t('system.marketChannel.delete') }}-->
          <!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
    <!--    新增/编辑弹框-->
    <DialogMarketChannel ref="dialogMarketChannelRef" @refresh="initialize" />
  </ContentWrap>
</template>

<script setup lang="ts">
import DialogMarketChannel from './components/DialogMarketChannel/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { changeStatusApi, delDataApi, getListApi } from '@/api/marketChannel'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])

const dialogMarketChannelRef = ref()

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  name: '',
  status: '',
  pageIndex: 1,
  pageSize: 20
})

const statusList = ref<Array<Record<string, any>>>([
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
])

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
//点击新增
const handleAdd = () => {
  nextTick(() => {
    dialogMarketChannelRef.value.getBackShow('add')
    dialogMarketChannelRef.value.dialogVisible = true
  })
}
//点击编辑
const handleEdit = (row: Record<string, any>) => {
  nextTick(() => {
    dialogMarketChannelRef.value.getBackShow('edit', JSON.parse(JSON.stringify(row)))
    dialogMarketChannelRef.value.dialogVisible = true
  })
}
//批量操作
const handleBatch = async (type: string) => {
  const functionMap = {
    open: () => handleChangeStatus('open', { status: 1 }),
    close: () => handleChangeStatus('close', { status: 0 }),
    delete: () => handleDelete('batch', {})
  }
  if (functionMap[type]) functionMap[type]()
}
//点击删除
const handleDelete = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delDataApi({
        ids:
          type === 'single'
            ? [row.id]
            : multipleSelection.value.map((item: Record<string, any>) => item.id)
      })
      ElMessage.success(t('purchase.logistics.deleteSuccess'))
      await initialize()
    })
    .catch(() => {})
}

const handleChangeStatus = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(
    `是否确认状态流转为${row.status === 1 ? '启用' : '禁用'}？`,
    t('purchase.logistics.tips'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const resp = await changeStatusApi({
          ids:
            type === 'single'
              ? [row.id]
              : multipleSelection.value.map((item: Record<string, any>) => item.id),
          status: row.status
        })
        if (resp.code === 0) {
          ElMessage.success(t('market.industryNews.statusMsg'))
          await initialize()
        }
      } catch (e) {
        await initialize()
      }
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1
    })
}
//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const resp = await getListApi(form.value)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    name: '',
    status: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  initialize()
})
</script>

<style lang="less" scoped></style>
